import asyncio
import subprocess
import datetime
from setting import DEBUG_PRINT



def time_print(*args, **kwargs):
    """增强版print，自动添加logging风格的时间戳"""
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]  # 精确到毫秒
    print(f"{timestamp} - PRINT - ", *args, **kwargs)

# async def move_window_by_title(window_title, x, y, width=1500, height=250):
#     """使用 xdotool 移动窗口"""
#     cmd = f"xdotool search --name '{window_title}' windowmove {x} {y} windowsize {width} {height}"
#     subprocess.run(cmd, shell=True)

async def move_window_by_title(window_title, x, y, width=1500, height=250):
    """使用 xdotool 移动窗口"""
    if not window_title and window_title in ['about:blank', 'data:', '']:
        cmd = f"xdotool search --class 'chromium' windowmove {x} {y} windowsize {width} {height}"
    else:
        cmd = f"xdotool search --name '{window_title}' windowmove {x} {y} windowsize {width} {height}"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"move_window failed: {result.stderr}")
    else:
        print(f"move_window success: {window_title} -> ({x}, {y})")


async def get_window_position(window_title):
    """使用 xdotool 获取窗口坐标 (x, y)"""
    cmd = f"xdotool search --name '{window_title}' getwindowgeometry --shell"
    output = subprocess.check_output(cmd, shell=True).decode()
    
    # 解析输出结果（示例输出：X=100\nY=200\nWIDTH=800\nHEIGHT=600\n）
    x = int(output.split("X=")[1].split("\n")[0])
    y = int(output.split("Y=")[1].split("\n")[0])
    return (x, y)

async def getCategoryIndex(categoryURL):

    if '.html' in categoryURL:
        categoryIndex = categoryURL.split('/')[-1].replace('.html','').split('-page')[0]
    else:
        categoryIndex = '_'.join(categoryURL.split('page/')[0].split('/')[-3:-1])

    return categoryIndex

async def getPageUrl(categoryURL, pageIndex):

    if '.html' in categoryURL:
        pageUrl = categoryURL.replace('.html', f'-page-{pageIndex}.html')
    else:
        pageUrl = categoryURL + f'page/{pageIndex}/'

    return pageUrl


async def getPageIndex(pageURL):

    if '.html' in pageURL:
        pageIndex = int(pageURL.split('/')[-1].split('-')[-1].replace('.html',''))
    else:
        pageIndex = int(pageURL.split('/')[-2])
    return pageIndex


async def getPageID(categoryIndex, pageUrl):

    pageIndex = await getPageIndex(pageUrl)
    pageID = categoryIndex + '_' + str(pageIndex)
    
    return pageID

async def getCurrentIp(page):
    for i in range(3):
        try:
            response = await page.request.get("https://api.ipify.org?format=json")
            ip_data = await response.json()
            currentIp = ip_data["ip"]
            # currentIp = await page.evaluate("""() => fetch('https://ifconfig.me/ip').then(r => r.text())""")
            # currentIp = await page.evaluate("""() => fetch('https://ipv4.ifconfig.me/ip').then(r => r.text())""")
            return currentIp
        except:
            await asyncio.sleep(2)
            continue
    return ''

async def dynamic_route(route):
    route_request = route.request
    url = route_request.url
    if DEBUG_PRINT >= 3:
        print(f'1### {url}')
    if "humancheck_captcha" in url:
        if DEBUG_PRINT >= 3:
            print(f'2### 放行滑动验证页 {url}')
        await route.continue_()  # 放行验证页的所有资源
    # elif ".jpg?x-oss-process=style/c320" in url:
    #     if DEBUG_PRINT >= 3:
    #         print(f'3### 放行特殊图片 {url}')
    #     await route.continue_()
    elif any(ext in url for ext in [".png", ".jpg", ".jpeg", ".svg", ".gif", ".ico", ".css", ".mp4", ".php", "pagead", "interaction"]):
        if DEBUG_PRINT >= 3:
            print(f'3### 屏蔽png {url}')
        await route.abort()  # 拦截非关键静态资源
    # elif ".jpg" in url:
    #     if DEBUG_PRINT >= 3:
    #         print(f'5### 屏蔽普通 .jpg {url}')
    #     await route.abort()
    elif any(js in url for js in [".js"]):
        if DEBUG_PRINT >= 3:
            print(f'4### 屏蔽 js {url}')
        await route.abort()  # 拦截已知无关JS
    elif route_request.resource_type in ["image", "stylesheet", "font", "script", "fetch", "xhr"]:
        if DEBUG_PRINT >= 3:
            print(f'5### 屏蔽 request type : {route_request.resource_type}')
        await route.abort()  # 拦截非关键静态资源
    else:
        if DEBUG_PRINT >= 3:
            print(f'6### continue {url}')
        await route.continue_()  # 放行其他JS（包括验证依赖的JS）